package com.basemanage.conf;

import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.basemanage.core.shiro.kit.PasswordKit;
import com.basemanage.model.SysRole;
import com.basemanage.model.SysUser;
import com.jfinal.kit.LogKit;

public class ShiroDbRealm extends AuthorizingRealm {

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		String username = (String) principals.getPrimaryPrincipal();
		// 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		SysUser user = SysUser.dao.getByName(username);
		if (null == user) {
			return info;
		}

		List<SysRole> roles = SysRole.dao.getSysRoleList(user.getId());

		if (null != roles) {
			for (SysRole role : roles) {
				// 角色的名称及时角色的值
				info.addRole(role.getName());
			}
		}

		// 添加用户的所有资源
		Set<String> reses = SysUser.dao.getPermissionSets(user.getId());
		info.addStringPermissions(reses);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		//用户名
        String username = (String) authcToken.getPrincipal();
        LogKit.info("username:"+username);
        //密码
        String password = new String((char[])authcToken.getCredentials());
        LogKit.info("password:"+password);
        
		SysUser user = SysUser.dao.getByName(username);
		if (user == null) {
			throw new UnknownAccountException();// 没找到帐号
		}
	 
		return new SimpleAuthenticationInfo(user.getName(), // 用户名
				user.getPwd(), // 密码 
				ByteSource.Util.bytes(PasswordKit.ENCRYPT_SALT),
				getName() // realm name
		);
	}
}
